package com.example.demo.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname PrintThreadByLock1
 * @Description
 * @Date 2023/12/12 14:11
 * @Created by jyl
 */
public class PrintThreadByLock1 implements Runnable {
    private static final Lock LOCK = new ReentrantLock();

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            LOCK.lock();
            try {
                System.out.println("线程1：" + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                LOCK.unlock();
            }
        }
    }

    public static class PrintThreadByLock2 implements Runnable {
        private static final Lock LOCK = new ReentrantLock();

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                LOCK.lock();
                try {
                    System.out.println("线程2：" + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    LOCK.unlock();
                }
            }
        }

    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new PrintThreadByLock1());
        Thread thread2 = new Thread(new PrintThreadByLock2());
        thread1.start();
        thread2.start();
    }
}
